package com.example.productmanagerspringboot.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@Api(tags = "上传")
public class FileUploadController {
    private static final String UPLOADED_FOLDER = "F://upload/";

    @PostMapping("/upload")
    @Operation(summary = "上传图片")
//    @ApiImplicitParams(@ApiImplicitParam(paramType = "body", name = "photo", value = "图片文件", dataTypeClass = MultipartFile.class))
    public String upload(@ApiParam(value = "图片文件", required = true) @RequestPart("photo") MultipartFile photo) throws IOException {
//        String realPath = request.getServletContext().getRealPath("/upload/");
        saveFile(photo);
        System.out.println(UPLOADED_FOLDER + photo);
        return photo.getOriginalFilename();
    }


//    @GetMapping("/get")
    public void saveFile(MultipartFile file) throws IOException {
        File upDir = new File(UPLOADED_FOLDER);
        if (!upDir.exists()) upDir.mkdir();
        File f = new File(UPLOADED_FOLDER + file.getOriginalFilename());
        file.transferTo(f);
    }
}
